<template>
  <CommonDialog v-model="visible" title="编辑标签" :width="500" submitText="确定" @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :label-width="0">
      <FormItem>
        <p>新增标签(请输入标签，最多32个字符，可通过回车添加)</p>
        <Input v-model="formData.kbtag" type="textarea" maxlength="32" show-word-limit :rows="4"
          placeholder="请输入标签，可通过回车添加。每个标签最多32个字符,支持中文,大小写英文字母,数字,下划线_,中划线-,首尾空格会自动阶段" @on-enter="disposeTags" />

        <div>
          <Tag v-for="(item,index) in tagList" :key="index" type="border" closable
            @on-close="tagList.splice(index, 1)">{{ item }}
          </Tag>
        </div>
        <!-- <p>已使用的标签 (点击可添加)</p> -->
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref, inject } from 'vue'
import { Message } from 'view-ui-plus'

import { myKnowledge } from '@/api/modules/knowledgeBase'

const emit = defineEmits(['cancel', 'submit'])

const props = defineProps({
  details: Object
})

const homeUpdate = inject('homeUpdate')
// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  kbtag: ''
})

let tableId = null

const tagList = ref([])
const disposeTags = () => {
  if (!formData.value.kbtag) return

  const text = formData.value.kbtag.trim()
  try {
    const tags = text.split(',').filter(item => item)
    tagList.value.push(...tags)
    formData.value.kbtag = ''
  } catch (error) {
    Message.error('请使用,隔开')
  }
}
/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    await myKnowledge.fileedit({
      data: {
        kbtag: tagList.value.toString(),
        id: tableId
      }
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  emit('cancel')
}

const initData = (data = {}) => {
  tableId = data.id
  visible.value = true
  
  if(!data.kbtag) return
  tagList.value = data.kbtag.split(',')
}

defineExpose({
  initData
})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}

::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>